import {messages} from "share/common";
/**
 * Created by Allen on 2018/1/18.
 */
import React from 'react'
import { connect } from 'react-redux';

import menuRoute from 'routes/menuRoute'
import { Button, Badge, message, Popconfirm, Icon, Row, Col, Select, InputNumber, Popover } from 'antd'
import SlideFrame from 'components/slide-frame'
import NewRule from 'containers/expense-reimbursement-control/expense-standard/travel-policy/new-rule'
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'
const Option = Select.Option;
import ResizeTable from 'components/resize-table'

class RulesList extends React.Component{
  constructor(props){
    super(props);

    this.state = {
      loading: false,
      showSlideFrame: false,
      type: null,
      data: [],
      nowRule: {},
      hotelTypeData: {},
      isShowHotelTypes: false,
      isEditType: false, //是否编辑酒店的计算标准
      participantRuleCode: '', //内部参与人多条标准时
      externalParticipantRuleCode: '', //外部参与人标准
      multiConsolidatedRuleCode: '', //多个参与人统一订票时
      multiConsolidatedRuleAmount: 100, //多个参与人统一订票时的百分比
      multiIndividualRuleCode: '', //多个参与人各自订票时
      hotelData: {}, //酒店配置的data，点击取消的时候还原数据需要
      page: 0,
      pageSize: 10,
      pagination: {
        current: 0,
        total: 0
      },
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: '5%',render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page}, //序号
        {title: messages('setting.key1186'/*业务描述*/), dataIndex: 'comment', width: '15%'}, //业务描述
        {title: messages('setting.key1187'/*适用人群*/), dataIndex: 'travelRuleRelations', width: '15%',
          render: (value,record) => (
            this.renderUser(value,record)
        )}, //适用人群
        {title: messages('expense-reimbursement-control.key54')/*适用公司*/, dataIndex: 'travelRuleCompanyList', width: '10%',
          render: (value,record) => (
            this.renderCompany(value, record)
        )}, //适用公司
        {title: messages('common.from')/*来源*/, dataIndex: 'source', width: '10%', align: "right",
          render: (value, record) => {
            return value === 1001 ? (<span>{messages('expense-reimbursement-control.key74')/*账套*/}</span>) : (<span>{messages('expense-reimbursement-control.key75')/*公司*/}</span>)
        }}, //来源
        {title: messages('common.column.status'), dataIndex: 'status', width: '10%', align: "right",
          render: (value,record) => (
            <Badge status={value === 1001 ? 'success' : 'error'}
                   text={value === 1001 ? messages('common.enabled') : messages('common.disabled')}/>)
        }, //状态
        {title: messages('common.operation'), dataIndex: 'operation', key: 'operation',"align":"center",
          render: (text, record) => (
            <span>
              {!props.tenantMode && record.source === 1001 && (
                <span>
                  <a onClick={(e) => this.handleEdit(e, record)}>{messages('common.view')/*查看*/}</a>
                </span>
              )}
              {(props.tenantMode || record.source !== 1001) && (
                <span>
                  <a onClick={(e) => this.handleEdit(e, record)}>{messages('common.edit')}</a>
                  <span className="ant-divider"/>
                  <a onClick={(e) => this.handleNewEdit(e, record)}>{messages('setting.key1188'/*复制并编辑*/)}</a>
                  <span className="ant-divider"/>
                  <Popconfirm onConfirm={(e) => this.handleDelete(e, record)} title={messages('setting.key1189'/*你确认要删除？*/)}>{/* 你确定要删除organizationName吗 */}
                    <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')}</a>
                  </Popconfirm>
                </span>
              )}
            </span>)
        },  //操作
      ],
      rulesList: menuRoute.getRouteItem('rules-list','key'),
      travelStandard: menuRoute.getRouteItem('expense-standard','key')
    }
  }

  componentWillMount(){
    const { params } = this.props;
    if (params.id === '1001'){
      this.setState({type: messages('setting.key686'/*机票*/)});
    } else if (params.id === '1002'){
      this.setState({type: messages('setting.key717'/*火车*/)});
    } else if (params.id === '1003'){
      this.setState({type: messages('setting.key707'/*酒店*/)});
      this.getCityOptions();
      this.initIsShow();
      this.getHotelTypes();
      this.getHotelTypesScope();
    } else if (params.id === '1008'){
      this.setState({type: messages('expense-reimbursement-control.key110')/*用车*/});
      this.addFormColumn();
    }
    this.setState({
      travelItineraryStandID: this.props.routeParams.travelItineraryStandID,
      id: this.props.routeParams.id
    }, () => {
      this.getList();
    });
  }

  //用车要多展示一列适用表单
  addFormColumn = () => {
    const { columns } = this.state;
    let formColumnInfo = {
      title: messages('expense-reimbursement-control.key99')/*适用表单*/,
      width: '10%',
      dataIndex: 'customFormDTOs',
      render: (value, record) => {
        if (record.visibleFormScope === 1){
          return <span>{messages('setting.key1037'/*通用*/)}</span>
        }else {
          let formNameList = [];
          if (value) {
            value.map((item, index) => {
              if (item.formOID) {
                formNameList.push(item.formName);
              }
            });
          }
          return <Popover placement="topLeft" content={formNameList.join(',')}>{formNameList.join(',')}</Popover>
        }
      }
    };
    columns.splice(5, 0, formColumnInfo);
    this.setState({columns});
  };

  initIsShow = () => {
    const { profile, tenantMode } = this.props;
    if ((tenantMode && !profile['travel.policy.mode']) ||
      (!tenantMode && profile['travel.policy.mode'])) {
      this.setState({isShowHotelTypes: true});
    } else {
      this.setState({isShowHotelTypes: false});
    }
  };

  //获取酒店配置数据
  getHotelTypes = () => {
    const { params } = this.props;
    if (params.travelItineraryStandID) {
      travelPolicyService.getHotelTypes(params.travelItineraryStandID).then((resp) => {
        this.setState({
          hotelData: resp.data,
          participantRuleCode: resp.data.participantRule,
          externalParticipantRuleCode: resp.data.externalParticipantRule,
          multiConsolidatedRuleCode: resp.data.multiConsolidatedRule,
          multiConsolidatedRuleAmount: resp.data.multiRate ? resp.data.multiRate : 100,
          multiIndividualRuleCode: resp.data.multiIndividualRule
        })
      });
    }
  };

  //获取酒店标准下拉框的选择范围数据
  getHotelTypesScope = () => {
    travelPolicyService.getHotelTypesScope().then((resp) => {
      this.setState({hotelTypeData: resp.data});
    });
  };

  //选择酒店的差旅标准
  handleSelectType = (value, key) => {
    this.setState({[key]: value});
  };

  //修改百分比
  handleChangeAmount = (num) => {
    this.setState({multiConsolidatedRuleAmount: num});
  };

  //toggle编辑状态
  //isRollBack 点击取消的时候需要还原配置数据
  handleToggleEditType = (isEdit, isRollBack) => {
    const { hotelData } = this.state;
    this.setState({isEditType: isEdit});
    if (isRollBack) {
      this.setState({
        participantRuleCode: hotelData.participantRule,
        externalParticipantRuleCode: hotelData.externalParticipantRule,
        multiConsolidatedRuleCode: hotelData.multiConsolidatedRule,
        multiConsolidatedRuleAmount: hotelData.multiRate ? hotelData.multiRate : 100,
        multiIndividualRuleCode: hotelData.multiIndividualRule
      });
    }
  };

  handleSave = () => {
    const { params } = this.props;
    const { participantRuleCode, externalParticipantRuleCode, multiConsolidatedRuleCode, multiConsolidatedRuleAmount,
      multiIndividualRuleCode } = this.state;
    if (participantRuleCode && externalParticipantRuleCode && multiConsolidatedRuleCode && multiConsolidatedRuleAmount
      && multiIndividualRuleCode) {
      let saveParams = {
        id: params.travelItineraryStandID,
        participantRule: participantRuleCode,
        externalParticipantRule: externalParticipantRuleCode,
        multiConsolidatedRule: multiConsolidatedRuleCode,
        multiRate: multiConsolidatedRuleAmount,
        multiIndividualRule: multiIndividualRuleCode
      };
      travelPolicyService.saveHotelTypes(saveParams).then((resp) => {
        message.success(messages('expense-reimbursement-control.key76')/*保存成功*/);
        this.setState({hotelData: saveParams});
        this.handleToggleEditType(false);
      });
    } else {
      message.error(messages('expense-reimbursement-control.key77')/*有未填项*/);
    }
  };

  //获取列表数据
  getList(){
    const { page, pageSize, travelItineraryStandID} = this.state;
    this.setState({loading: true});
    travelPolicyService.getStandardRuleList(page,pageSize,travelItineraryStandID).then((resp) => {
      resp.data.map((item,index) => {
        item.key = item.id
      });
      this.setState({
        data: resp.data,
        loading: false,
        pagination: {
          current: this.state.page + 1,
          total: Number(resp.headers['x-total-count']),
          onChange: this.onChangePager
        }
      })
    })
  }

  //表格渲染适用人群
  renderUser(value, record){
    if (value && value.length) {
      if (value[0].type === 1001){
        return <span>{messages('setting.key1037'/*通用*/)}</span>
      }else {
        let relationNameList = [];
        if (value) {
          value.map((item, index) => {
            if (item.relationOID) {
              relationNameList.push(item.relationName);
            }
          });
        }
        return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
      }
    } else {
      return null;
    }
  }

  //表格渲染适用公司
  renderCompany = (value, record) => {
    if (value && value.length) {
      let relationNameList = [];
      if (value) {
        value.map((item, index) => {
          if (item.companyId) {
            relationNameList.push(item.companyName);
          }
        });
      }
      return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
    } else {
      return <span>{messages('setting.key1037'/*通用*/)}</span>
    }
  };

  //获取城市级别
  getCityOptions = () => {
    travelPolicyService.getCityLevels().then((resp) => {
      resp.data.unshift(
        {levelName: '通用',id: '000000000'},
        {levelName: '其他',id: '111111111'});
      this.setState({cityOptions: resp.data});
    })
  };

  //点击分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getList()
      })
  };

  refreshNowRule = () => {
    const { nowRule } = this.state;
    nowRule.showSlideFrame = false;
    this.setState({nowRule: nowRule});
  };

  //新建
  handleNew = () => {
    const { params } = this.props;
    this.setState({
      showSlideFrame: true,
      isNew: true,
      nowRule: {
        showSlideFrame: true,
        isNew: true,
        type: 'standard',
        id: this.state.id,
        setOfBooksId: params.setOfBooksId,
        cityOptions: this.state.cityOptions,
        travelItineraryStandID: this.state.travelItineraryStandID,}})
  };

  //编辑
  handleEdit = (e, record) => {
    const { params } = this.props;
    this.setState({
      showSlideFrame: true,
      isNew: false,
      nowRule: {
        showSlideFrame: true,
        isNew: false,
        type: 'standard',
        id: this.state.id,
        setOfBooksId: params.setOfBooksId,
        cityOptions: this.state.cityOptions,
        travelItineraryStandID: this.state.travelItineraryStandID,
        record: record}})
  };

  //复制并编辑
  handleNewEdit = (e, record) => {
    const { params } = this.props;
    this.setState({
      showSlideFrame: true,
      isNew: true,
      nowRule: {
        showSlideFrame: true,
        isNew: true,
        type: 'standard',
        id: this.state.id,
        setOfBooksId: params.setOfBooksId,
        cityOptions: this.state.cityOptions,
        travelItineraryStandID: this.state.travelItineraryStandID,
        record: record}})
  };

  //删除
  handleDelete = (e,record) => {
    this.setState({loading: true});
    travelPolicyService.deleteTravelStandardRule(record.id).then((resp) => {
      if (resp.status === 200){
        this.setState({loading: false});
        message.success(messages('setting.key213'/*删除成功*/));
        this.getList();
      }
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages('common.operate.filed'));
    })
  };

  handleCloseSlide = (success) => {
    success && this.getList();
    this.setState({ showSlideFrame : false}, ()=>{this.refreshNowRule()});
  };

  handleBack = () => {
    this.context.router.push(`${this.state.travelStandard.url}`)
  };

  render(){
    const { loading, data, pagination, columns, isNew, showSlideFrame, nowRule, type, hotelTypeData, participantRuleCode,
      externalParticipantRuleCode, multiConsolidatedRuleCode, multiIndividualRuleCode, multiConsolidatedRuleAmount,
      isEditType, isShowHotelTypes } = this.state;
    const { params } = this.props;
    return (
      <div>
        <div className="header-title">
          {type} {messages('setting.key1190'/*差旅标准规则*/)}
          {!isEditType && params.id === '1003' && isShowHotelTypes && (
            <span className='default-color-font' style={{cursor: 'pointer', fontSize: '14px'}} onClick={() => this.handleToggleEditType(true)}>
              &nbsp;&nbsp;&nbsp;{messages('common.edit'/*编辑*/)}
            </span>
          )}
        </div>
        {params.id === '1003' && isShowHotelTypes && (
          <div>
            <Row style={{marginBottom: '15px'}}>
              <Col span={4} style={{lineHeight: '32px'}}>{messages('expense-reimbursement-control.key78')/*内部参与人多条标准时：*/}</Col>
              <Col span={6}>
                <Select style={{width: '100%'}}
                        allowClear
                        placeholder={messages('common.please.select')/*请选择*/}
                        filterOption={false}
                        disabled={!isEditType}
                        value={participantRuleCode ? participantRuleCode : undefined}
                        onChange={(value) => this.handleSelectType(value, 'participantRuleCode')}
                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {hotelTypeData.participantRuleTypes && hotelTypeData.participantRuleTypes.map(
                    type => <Option value={type.code} key={type.code}>{type.name}</Option>
                  )}
                </Select>
              </Col>
            </Row>
            <Row style={{marginBottom: '15px'}}>
              <Col span={4} style={{lineHeight: '32px'}}>{messages('expense-reimbursement-control.key79')/*外部参与人标准：*/}</Col>
              <Col span={6}>
                <Select style={{width: '100%'}}
                        allowClear
                        placeholder={messages('common.please.select')/*请选择*/}
                        filterOption={false}
                        disabled={!isEditType}
                        value={externalParticipantRuleCode ? externalParticipantRuleCode : undefined}
                        onChange={(value) => this.handleSelectType(value, 'externalParticipantRuleCode')}
                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {hotelTypeData.externalParticipantRuleTypes && hotelTypeData.externalParticipantRuleTypes.map(
                    type => <Option value={type.code} key={type.code}>{type.name}</Option>
                  )}
                </Select>
              </Col>
            </Row>
            <Row style={{marginBottom: '15px'}}>
              <Col span={4} style={{lineHeight: '32px'}}>{messages('expense-reimbursement-control.key80')/*多个参与人统一订票时：*/}</Col>
              <Col span={6}>
                <Select style={{width: '100%'}}
                        allowClear
                        placeholder={messages('common.please.select')/*请选择*/}
                        filterOption={false}
                        disabled={!isEditType}
                        value={multiConsolidatedRuleCode ? multiConsolidatedRuleCode : undefined}
                        onChange={(value) => this.handleSelectType(value, 'multiConsolidatedRuleCode')}
                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {hotelTypeData.multiConsolidatedRuleTypes && hotelTypeData.multiConsolidatedRuleTypes.map(
                    type => <Option value={type.code} key={type.code}>{type.name}</Option>
                  )}
                </Select>
              </Col>
              <Col span={4} style={{lineHeight: '32px'}}>
                &nbsp;*&nbsp;
                <InputNumber placeholder={messages('common.please.input')}
                             onChange={this.handleChangeAmount}
                             disabled={!isEditType}
                             value={multiConsolidatedRuleAmount}
                             precision={2}
                             max={9999}
                             min={0.01}/>
                &nbsp;%
              </Col>
            </Row>
            <Row style={{marginBottom: '15px'}}>
              <Col span={4} style={{lineHeight: '32px'}}>{messages('expense-reimbursement-control.key81')/*多个参与人各自订票时：*/}</Col>
              <Col span={6}>
                <Select style={{width: '100%'}}
                        allowClear
                        placeholder={messages('common.please.select')/*请选择*/}
                        filterOption={false}
                        disabled={true}
                        value={multiIndividualRuleCode ? multiIndividualRuleCode : undefined}
                        onChange={(value) => this.handleSelectType(value, 'multiIndividualRuleCode')}
                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {hotelTypeData.multiIndividualRuleTypes && hotelTypeData.multiIndividualRuleTypes.map(
                    type => <Option value={type.code} key={type.code}>{type.name}</Option>
                  )}
                </Select>
              </Col>
            </Row>
            {isEditType && (
              <Row style={{marginBottom: '15px'}}>
                <Button type="primary" onClick={this.handleSave}>{messages('common.save'/*保存*/)}</Button>
                <Button style={{marginLeft: '20px'}} onClick={() => this.handleToggleEditType(false, true)}>{messages('common.cancel'/*取消*/)}</Button>
              </Row>
            )}
          </div>
        )}
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total:pagination.total})}</div>
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew}>{messages('setting.key1191'/*新增规则*/)}</Button>{/*新建*/}
          </div>
        </div>

        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          rowKey={record => record.id}
          bordered
          size="middle"
        />
        <a style={{fontSize:'14px',paddingBottom:'20px'}} onClick={this.handleBack}>
          <Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')}
        </a>
        <SlideFrame content={NewRule}
                    title={isNew ? messages('setting.key1191'/*新增规则*/) : messages('setting.key1192'/*编辑规则*/)}
                    show={showSlideFrame}
                    onClose={()=>this.setState({showSlideFrame:false}, ()=>{this.refreshNowRule()})}
                    afterClose={this.handleCloseSlide} params={nowRule}/>
      </div>
    )
  }
}

RulesList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(RulesList);
